import fg from "fast-glob";
import fs from "fs-extra";
import path from "path";
import { toolchain } from "../toolchain.js";
import { Status } from "../tools/Status.js";
import { loadImage } from "./loadImage.js";
import { default as ssim } from "image-ssim";

interface IRes {
    file: string;
    similarity: number;
}

export class ImageFinder {
    public async findIt(): Promise<void> {
        if (toolchain.opts.target == null) {
            console.error('No target specified.');
            return;
        }

        const tgtContext = await loadImage(toolchain.opts.target);
        if (tgtContext == null) {
            console.error('Failed to load target image.');
            return;
        }

        let root = toolchain.opts.input ?? 'Assets';
        if (!path.isAbsolute(root)) {
            root = path.join(toolchain.opts.projectRoot, root);
        }
        const imgs = await fg(['**/*.png', '**/*.jpg'], { cwd: root });
        // 比较
        const results: IRes[] = [];
        Status.Instance.startTask('Compare images', imgs.length);
        for (const img of imgs) {
            Status.Instance.update(img);
            const file = path.join(root, img);
            const imgContext = await loadImage(file);
            if (imgContext == null) {
                console.error(`Failed to load image: ${file}`);
                continue;
            }
            const rst = ssim.compare(tgtContext, imgContext);
            results.push({ file, similarity: rst.ssim });
        }

        if (results.length > 0) {
            results.sort((a, b) => b.similarity - a.similarity); // 从大到小排序
            await fs.writeFile(`tmp/${toolchain.opts.projectName}.findImage.txt`, JSON.stringify(results, null, 4));
            for (const res of results) {
                if (res.similarity > .8) console.log(`Found similar image: ${res.file}`);
            }
        }
    }
}